package com.bdqn.jwt1.service;

import com.bdqn.jwt1.entity.Menu;
import com.bdqn.jwt1.entity.Role;
import com.bdqn.jwt1.entity.TUser;
import com.bdqn.jwt1.mapper.TUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class TUserService implements UserDetailsService {
    @Autowired
    TUserMapper tUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库中查询用户
        TUser tuser = tUserMapper.findByUsername(username);
        if (tuser == null) {
            throw new UsernameNotFoundException("账号不存在");
        }
        //从数据库中查询到该用户的所有角色(含权限）
        tuser.setRoles(tUserMapper.findRolesByUserId(tuser.getUid()));
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        //取出用户的角色，封装到authorities中
        for (Role role : tuser.getRoles()) {
            //添加角色
            authorities.add(new SimpleGrantedAuthority(role.getName()));
            //如果权限控制到权限菜单级别，则要补充这个
            for (Menu menu : role.getMenus()) {
                //添加权限
                authorities.add(new SimpleGrantedAuthority(menu.getMenuname()));
            }
        }
        //下面的密码一般要加密
        return new User(tuser.getUsername(), new BCryptPasswordEncoder().encode(tuser.getPassword()), authorities);
    }

    //根据用户id号查询用户的所有角色
    public List<Role> findRolesByUserId(int id) {
        return tUserMapper.findRolesByUserId(id);
    }

    //查找所有用户
    public List<TUser> findAllUsers() {
        return tUserMapper.findAllUsers();
    }

    //转换成自身业务的Tuser
    public TUser toTuser() {
        TUser tUser = (TUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return tUserMapper.findByUsername(tUser.getUsername());
    }
}
